import { createMemo, JSX, mergeProps, splitProps } from "solid-js";
import { A, useLocation, useMatch } from "@solidjs/router";
import { AppBase } from "@src/utils/NavigationHelper";

const NavLink = (
  p: JSX.LinkHTMLAttributes<HTMLLinkElement> & {
    prefixMatch?: string;
    active?: boolean
  }
) => {
  const [local, props] = splitProps(mergeProps({ prefixMatch: "prefix" }, p), [
    "prefixMatch",
    "active"
  ]);

  const location = useLocation();

  const mapped = createMemo(() => {
    const mid = `${AppBase}${props.href ?? ""}`;
    return mid.startsWith("/") ? mid : `/${mid}`;
  });

  const active = createMemo(() => {
    if (local.prefixMatch === "all") {
      return true;
    }

    if (!location.pathname) {
      return false;
    }

    const matched = location.pathname.startsWith(mapped());

    // console.log("match path", location.pathname, matched, mapped());

    return matched || local.active;
  });

  const classList = createMemo(() => {
    return {
      active: active(),
    };
  });

  return (
    <A class="nav-link" classList={classList()} href={props.href ?? ""}>
      {props.children}
    </A>
  );
};

export default NavLink;
